$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'baseinfo/lhpwaysectrole/list',
        datatype: "json",
        colModel: [
			{ label: '路段角色名称', name: 'waysectRoleName', index: 'WAYSECT_ROLE_NAME', width: 80 },
			{ label: '高德坐标经度', name: 'xgaode', index: 'X_gaode', width: 80 },
			{ label: '高德坐标纬度', name: 'ygaode', index: 'Y_gaode', width: 80 },
			{ label: '缩放等级', name: 'zoomLevel', index: 'zoom_level', width: 80 },
            { label: '是否启用', name: 'isActive', index: 'IS_ACTIVE', width: 80 ,formatter: function(value, options, row){
                    return value == 0 ?
                        '<span class="label label-success">正常</span>' :
                        '<span class="label label-danger">禁用</span>';
                } }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl",
            name:"roadName"
        }
    },
    check: {
        enable: true,
        chkStyle: "checkbox",
        chkboxType: { "Y": "s", "N": "s" }
    }
};
var ztree;

var settingu = {
    data: {
        simpleData: {
            enable: true,
            idKey: "userId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl",
            name:"username"
        }
    },
    check: {
        enable: true,
        chkStyle: "checkbox",
        chkboxType: { "Y": "s", "N": "s" }
    }
};
var ztreeu;

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		lhpWaysectRole: {},
        po:{
		    roleId:null,
            waysectIds:null
		},
        pu:{
            roleId:null,
            userIds:null
        }
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.lhpWaysectRole = {
			    isActive:'0'
            };
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
        relationWaysect:function(event){
            vm.getWaysect();
        },
        relationUser:function(event){
            vm.getUser();
        },
        getWaysect: function(event){
            var id = getSelectedRow();
            vm.po.roleId=id;
            if(id == null){
                return ;
            }
            //加载路段树
            $.get(baseURL + "baseinfo/lhphighwaysection/waysectTree", function(r){
                ztree = $.fn.zTree.init($("#waysectTree"), setting, r);
                //查询关联的路段
                var list;
                $.ajaxSettings.async = false;
                $.get(baseURL + "baseinfo/lhprolewaysectrelation/getByRoleId/"+id, function(r){
                   list=r.list;
                })
                $.ajaxSettings.async = true;
                for(var i=0;i<list.length;i++){
                    var node = ztree.getNodeByParam("id", list[i].waysectId);
                    if(node != null){
                       ztree.checkNode(node,true)
                    }
                }
                vm.waysectTree();
            })
        },
        waysectTree: function() {
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择路段",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#waysectLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var nodes=ztree.getCheckedNodes();
                    var waysectIds='';
                   for (var i=0;i<nodes.length;i++){
                       if(i==0){
                           waysectIds+=nodes[i].id;
                       }else {
                           waysectIds=waysectIds+","+nodes[i].id;
                       }
                   }
                   vm.po.waysectIds=waysectIds;
                   //修改关联
                    $.ajax({
                        type: "POST",
                        url:baseURL+ "baseinfo/lhprolewaysectrelation/updateRelation",
                        data: vm.po,
                        success: function(r){
                            if(r.code === 0){
                                layer.msg("操作成功", {icon: 1});
                            }else{
                                layer.alert(r.msg);
                            }
                        }
                    });
                    layer.close(index);
                }

            });
        },
        getUser: function(event){
            var id = getSelectedRow();
            vm.pu.roleId=id;
            if(id == null){
                return ;
            }
            //加载用户
            $.get(baseURL + "sys/user/userTree", function(r){
                ztreeu = $.fn.zTree.init($("#userTree"), settingu, r.list);
                //查询关联的用户
                var list;
                $.ajaxSettings.async = false;
                $.get(baseURL + "baseinfo/lhpuserwaysectrolerelation/getByRoleId/"+id, function(r){
                    list=r.list;
                })
                $.ajaxSettings.async = true;
                for(var i=0;i<list.length;i++){
                    var node = ztreeu.getNodeByParam("userId", list[i].userId);
                    if(node != null){
                        ztreeu.checkNode(node,true)
                    }
                }
                vm.userTree();
            })
        },
        userTree: function() {
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择路段",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#userLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var nodes=ztreeu.getCheckedNodes();
                    var userIds='';
                    for (var i=0;i<nodes.length;i++){
                        if(i==0){
                            userIds+=nodes[i].userId;
                        }else {
                            userIds=userIds+","+nodes[i].userId;
                        }
                    }
                    vm.pu.userIds=userIds;
                    //修改关联
                    $.ajax({
                        type: "POST",
                        url:baseURL+ "baseinfo/lhpuserwaysectrolerelation/updateRelation",
                        data: vm.pu,
                        success: function(r){
                            if(r.code === 0){
                                layer.msg("操作成功", {icon: 1});
                            }else{
                                layer.alert(r.msg);
                            }
                        }
                    });
                    layer.close(index);
                }

            });
        },
		saveOrUpdate: function (event) {
		    $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                var url = vm.lhpWaysectRole.id == null ? "baseinfo/lhpwaysectrole/save" : "baseinfo/lhpwaysectrole/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.lhpWaysectRole),
                    success: function(r){
                        if(r.code === 0){
                             layer.msg("操作成功", {icon: 1});
                             vm.reload();
                             $('#btnSaveOrUpdate').button('reset');
                             $('#btnSaveOrUpdate').dequeue();
                        }else{
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "baseinfo/lhpwaysectrole/delete",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},
		getInfo: function(id){
			$.get(baseURL + "baseinfo/lhpwaysectrole/info/"+id, function(r){
                vm.lhpWaysectRole = r.lhpWaysectRole;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		}
	}
});